import {setStore, getStore} from '@/utils/storage.js'
import {hex_md5} from '../utils/md5.js'
let signature = '';
if (uni.getStorageSync('signature')) {
	signature = uni.getStorageSync('signature')
} else {
	signature = hex_md5(new Date().getTime().toString());
	uni.setStorageSync('signature', signature)
}
var http = {
	config: {
		baseUrl: '',
		header: {
			'Content-Type':'application/json;charset=UTF-8',
			'Content-Type':'application/x-www-form-urlencoded'
		},  
		data: {},
		method: "GET",
		dataType: "json",  /* 如设为json，会对返回的数据做一次 JSON.parse */
		responseType: "text",
		success() {},
		fail() {},
		complete() {}
	},
	//路由 不拦截登录的页面
	filterPages: [],
	interceptor: {
		request: null,
		response: null
	},
	request(options) {
		if (!options) {
			options = {}
		}
		options.baseUrl = options.baseUrl || http.config.baseUrl
		options.dataType = options.dataType || http.config.dataType
		// if(!/^http/.test(options.url)){
		// 	options.url = options.baseUrl + options.url
		// }
		options.url = uni.getStorageSync('available_domain') + options.url
		options.data = options.data || {}
		options.method = options.method || http.config.method
		//TODO 加密数据
		return new Promise((resolve, reject) => {
			let _config = null
			var storeKey = options.storeKey
			if(options.getStore){
				let getStoreData = getStore(storeKey, options.store == 2)
				options.getStore(getStoreData)
			}
			
			options.complete = (response) => {
				let statusCode = response.statusCode
				response.config = _config
				if (http.interceptor.response) {
					let newResponse = http.interceptor.response(response)
					if (newResponse) {
						response = newResponse
					}
				}
				if (statusCode === 200) { //成功
					if(response.data.code == -1){
						let pages = getCurrentPages()
						//#ifdef H5
							let currentRouter = pages[0].$page.path
						//#endif
						//#ifdef APP-PLUS
							let currentRouter = pages[pages.length - 1].route
						//#endif
						if(http.filterPages.indexOf(currentRouter) == -1){
							uni.redirectTo({
								url: '/pages/login/index',
							});
						}
						reject(response.data)
					} else if(response.data.code == 200){
						resolve(response.data);
						if(options.store){
							//如果是分页数据, 只缓存第一页
							if(response.data.data && response.data.data.current_page){
								if(((options.data.page && options.data.page==1) || !options.data.page)){
									setStore(storeKey, response.data.data.data, options.store == 2)
								}
							}else{
								setStore(storeKey, response.data.data, options.store == 2)
							}
						}
					} else {
						if(((options.data.set && options.data.set=='no'))){
							
						}else{
							uni.showToast({
								title: response.data.msg,
								mask: false,
								icon: 'none'
							});
						}
						reject(response.data)
					}
				} else {
					// uni.showToast({
					// 	title: '网络错误',
					// 	mask: false,
					// 	icon: 'none'
					// });
					reject()
				}
			}
			_config = Object.assign({}, http.config, options)
			_config.requestId = new Date().getTime()
	
			if (http.interceptor.request) {
				http.interceptor.request(_config)
			}
			uni.request(_config);
		});
	},
	formatOption(url, data, options) {
		let storeKey = url.replace(options.baseUrl, '')
		storeKey = storeKey.replace(/\//g, '_')
		
		let lang = uni.getStorageSync('lang') || 'zh-cn'
		url += (url.indexOf('?') === -1) ? `?lang=${lang}` : `&lang=${lang}`;
		
		options.url = url
		options.data = data
		
		for(let dataKey in options.data){
			if(dataKey != 'token' && dataKey != 'page'){
				storeKey += '_'+dataKey+'_'+options.data[dataKey]
			}
		}
		options.storeKey = options.storeKey ? options.storeKey : storeKey
	},
	get(url, data = {}, options = {}) {
		http.formatOption(url, data, options)
		
		options.header = Object.assign((options.header || {}), {
			token: uni.getStorageSync('token')
		})
		options.method = 'GET'  
		return http.request(options)
	},
	post(url, data = {}, options = {}) {
		http.formatOption(url, data, options)
		
		if(/^\/{0,1}ex/.test(url) || /^http/.test(url)){
			options.header = Object.assign((options.header || {}), {
				'Content-Type': 'application/x-www-form-urlencoded',
				'language': uni.getStorageSync('lang'),
			})
		}else{
			options.header = Object.assign((options.header || {}), {
				'Content-Type': 'application/x-www-form-urlencoded',
				token: uni.getStorageSync('token')
			})
		}
		options.method = 'POST'
		return http.request(options)
	},
	put(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'PUT'
		return http.request(options)
	},
	delete(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'DELETE'
		return http.request(options)
	}
}

export default http
